package com.t4.process.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.t4.common.exception.T4Exception;
import com.t4.common.result.Result;
import com.t4.model.process.ProcessTemplate;
import com.t4.process.service.ProcessTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "审批模板管理")
@RestController
@RequestMapping("/admin/process/processTemplate")
public class ProcessTemplateController {

    @Resource
    private ProcessTemplateService processTemplateService;

    @ApiOperation(value = "分页查询审批模板")
    @GetMapping("{current}/{size}")
    public Result queryParam(@PathVariable Long current,
                             @PathVariable Long size){
        Page<ProcessTemplate> pageParam = new Page<>(current, size);
        // 分页查询审批模板时，要将对应的审批类型名称查询出来
        IPage<ProcessTemplate> pageModel = processTemplateService.pageWithProcessType(pageParam);
        return Result.success(pageModel);
    }

    @ApiOperation(value = "根据id查询审批模板")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id){
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        return Result.success(processTemplate);
    }

    @ApiOperation(value = "新增审批模板")
    @PostMapping("save")
    public Result save(@RequestBody ProcessTemplate processTemplate){
        boolean is_success = processTemplateService.save(processTemplate);
        if(is_success){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @ApiOperation(value = "修改审批模板")
    @PutMapping("update")
    public Result updateById(@RequestBody ProcessTemplate processTemplate){
        boolean is_success = processTemplateService.updateById(processTemplate);
        if(is_success){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @ApiOperation(value = "删除审批模板")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id){
        boolean is_success = processTemplateService.removeById(id);
        if(is_success){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    @ApiOperation(value = "上传流程定义")
    @PostMapping("uploadProcessDefinition")
    public Result uploadProcessDefinition(MultipartFile multipartFile) throws FileNotFoundException {
        // 获取classes目录位置
        String path = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
        // 设置上传文件夹
        File tempFile = new File(path + "/processes/");
        // 如果文件夹为空则进行创建
        if(!tempFile.exists()){
            tempFile.mkdirs();
        }
        // 获取上传的文件名称
        String filename = multipartFile.getOriginalFilename();
        // 创建空文件，用于实现文件写入
        File localFile = new File(path + "/processes/" + filename);
        // 保存文件流到本地
        try {
            multipartFile.transferTo(localFile);
        } catch (IOException e) {
            return Result.fail();
        }
        // 根据上传地址后续部署流程定义，文件名称为流程定义的默认key
        Map<String, Object> map = new HashMap<>();
        map.put("processDefinitionPath", "processes/" + filename);
        map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));

        return Result.success(map);
    }

    @ApiOperation(value = "部署流程定义并发布")
    @GetMapping("publish/{id}")
    public Result publish(@PathVariable Long id){
        // 1. 修改模板发布状态（1已经发布）
        // 2. 进行流程定义部署
        processTemplateService.publish(id);
        return Result.success();
    }

}
